<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
  <meta name="keywords" content="在线答题">
  <meta name="description" content="在线答题是一个完全响应式，基于Bootstrap3最新版本开发的扁平化主题，她采用了主流的左右两栏式布局，使用了Html5+CSS3等现代技术">
  <title>在线答题APP后台管理系统</title>
  <link rel="shortcut icon" href="favicon.ico">
  <link href="../Styles/css/bootstrap.min.css" rel="stylesheet">
  <link href="../Styles/css/font-awesome.min93e3.css?v=4.4.0" rel="stylesheet">
  <link href="../Styles/css/animate.min.css" rel="stylesheet">
  <link href="../Styles/css/style.min.css" rel="stylesheet">
  <link href="../Styles/css/plugins/sweetalert/sweetalert.css" rel="stylesheet">
</head>

<body class="gray-bg">
  <div class="wrapper wrapper-content animated fadeInRight">

    <div class="ibox-content">
      <form class="form-horizontal m-t" id="EditForm">
        <div class="form-group">
          <label class="col-sm-3 control-label">角色名称:</label>
          <div class="col-sm-8">
            <input id="Id" name="Id" type="hidden">
            <input id="RoleName" name="RoleName" class="form-control" type="text">
            <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 请输入角色名称且不能为空</span>
          </div>
        </div>
        <div class="form-group">
          <label class="col-sm-3 control-label">角色状态：</label>
          <div class="col-sm-8">
            <select class="form-control m-b" id="StateDisplay" name="StateDisplay">
              <option selected>可用</option>
              <option>不可用</option>
            </select>
            <span class="help-block m-b-none"><i class="fa fa-info-circle"></i> 请选择角色状态</span>
          </div>
        </div>
        <div class="form-group">
          <label class="col-sm-3 control-label">选择权限
          </label>
          <div class="col-sm-8">
            <div id="menuTree" name="menuTree"></div>
            <button class="btn btn-primary" type="button" id="btnAll">全选</button>
            <button class="btn btn-primary" type="button" id="btnUnAll">反选</button>
          </div>
        </div>
      </form>
    </div>
  </div>
  <script src="../Scripts/jquery.min.js"></script>
  <script src="../Scripts/bootstrap.min.js"></script>
  <script src="../Scripts/content.min.js"></script>
  <script src="../Scripts/plugins/validate/jquery.validate.min.js"></script>
  <script src="../Scripts/plugins/validate/messages_zh.min.js"></script>
  <script src="../Scripts/plugins/sweetalert/sweetalert.min.js"></script>
  <script src="../Scripts/plugins/treeview/bootstrap-treeview.js"></script>
  <script>
    //console.info(typeof(1));
    $(function () {
      $mtree = $("#menuTree");
      $("#EditForm").validate({
        rules: { //验证规则
          TypeName: {
            required: true
          },
          TypeState: {
            required: true
          }
        },
        messages: { //对应的提示
          TypeName: {
            required: "类型名称必填"
          },
          TypeState: {
            required: "状态必选"
          }
        }
      });
      $.get(currentUrl + 'Menus/GetAll', function (data) {
        //绑定菜单树
        $mtree.treeview({
          data: data,
          multiSelect: true,
          showCheckbox: true,
          showIcon: false,
          nodeIcon: "glyphicon glyphicon-unchecked",
          selectedIcon: "glyphicon glyphicon-check",
          checkedIcon: "glyphicon glyphicon-check",
          // collapseIcon:"",
          selectedBackColor: "white",
          selectedColor: '#676A6c',
          uncheckedIcon: "glyphicon glyphicon-unchecked",
          onNodeSelected: function (event, node) { //节点的选择事件
            //alert(node.id);
            // var selectNodes = getChildNodeIdAttr(node);
            // selectNodes.push(node.nodeId);
            // if(selectNodes){
            //   $mtree.treeview('toggleNodeChecked',[selectNodes,{silent:true}] );            
            // }
          },
          onNodeChecked: function (event, node) { //节点多选框选中事件，将其内部所有节点全部选中 全选
            var selectNodes = [];
            if (node.nodes) {
              selectNodes = selectNodes.concat(getChildNodeIdArr(node)); //获取所有其子节点
            }
            if (node.parentId != undefined) {
              selectNodes = selectNodes.concat(getParentNodeIdArr(node));
            }
            //获取其父(包括父亲或者更高级的)节点            
            if (selectNodes) {
              $mtree.treeview('checkNode', [selectNodes, {
                silent: true
              }]); //将其子(包括孙级或更低级的)节点          
            }
          },
          onNodeUnchecked: function (event, node) { //将其内部所有节点全部取消选中 反选
            if (node.nodes) {
              var selectNodes = getChildNodeIdArr(node); //插件提供的方法，表示插件自己可以根据方法名去做一些事情 方法内容是插件自带
              //插件提供的事件，表示需要开发者根据其名称实现符合意思的事情，事件内容是需要开发者自己写的
              selectNodes.push(node.nodeId);
              if (selectNodes) {
                $mtree.treeview('uncheckNode', [selectNodes, {
                  silent: true
                }]);
              }
            }
            //子级反选父级
            setParentNodeUnCheck(node);
          }

        });
      });
      $("#btnAll").click(function () {
        $mtree.treeview("checkAll", {
          silent: true
        });
      });
      $("#btnUnAll").click(function () {
        $mtree.treeview("uncheckAll", {
          silent: true
        });
      });
      //$mtree.treeview('uncheckAll',{silent:true});
      //加载该角色数据
      var id = window.location.href.split('?')[1].split('=')[1];
      $.get(currentUrl + 'Roles/' + id, function (data) {
        $("#Id").val(data.id);
        $("#RoleName").val(data.roleName);
        $("#StateDisplay").val(data.stateDisplay);
        if (data.mtree !== undefined && data.mtree !== "") {
          var menuid = data.mtree.split(','); //已有菜单的id属性值["1","11","14"]
          for (var x in menuid) {
            var node = $mtree.treeview('findNodesById', [menuid[x], 'g', "id"]);
            //console.info(node[0]);
            $mtree.treeview("checkNode", [node[0].nodeId, {
              silent: true
            }]);
          }
        }

      });

      //自定义方法
      //1、根据节点名称，查找对应的节点
      var findCheckableNodess = function (name) {
        return $mtree.treeview('search', [name, {
          ignoreCase: false,
          exactMatch: false
        }]);
      };
      //2、根据父节点全选子节点
      function getChildNodeIdArr(node) {
        var ts = [];
        if (node.nodes) {
          for (var x in node.nodes) {
            ts.push(node.nodes[x].nodeId);
            if (node.nodes[x].nodes) {
              var getNodeDieDai = getChildNodeIdArr(node.nodes[x]); //有第二层，第三层子节点的情况
              for (j in getNodeDieDai) {
                ts.push(getNodeDieDai[j]);
              }
            }
          }
        } else {
          ts.push(node.nodeId)
        }
        return ts;
      }
      //3、当前子节点全部选择则自动选中其父节点
      function setParentNodeCheck(node) {
        var parentNode = $mtree.treeview("getNode", node.parentId);
        if (parentNode.nodes) {
          var checkedCount = 0;
          for (x in parentNode.nodes) {
            if (parentNode.nodes[x].state.checked) {
              checkedCount++;
            } else {
              break;
            }
          }
          if (checkedCount === parentNode.nodes.length) {
            $mtree.treeview("checkNode", parentNode.nodeId);
            setParentNodeCheck(parentNode);
          }
        }
      }
      //4、根据当前节点获取其父(包括父亲节点与更高级)节点
      function getParentNodeIdArr(node) {
        var ts = [];
        //console.log(node.parentId);
        if (node.parentId != undefined) { //拥有父级菜单
          ts.push(node.parentId); //父级菜单编号
          var parentNode = $mtree.treeview("getNode", node.parentId);
          if (parentNode.parentId != undefined) {
            ts.push(parentNode.parentId); //祖父级菜单编号
          }
        }
        return ts;
      }
      //5、当前子节点全部取消选中，则自动将其父节点取消选中
      function setParentNodeUnCheck(node) {
        var parentNode = $mtree.treeview("getNode", node.parentId);
        if (parentNode.nodes) {
          var checkedCount = 0;
          for (x in parentNode.nodes) {
            if (parentNode.nodes[x].state.checked) {
              checkedCount++;
            } else {
              continue;
            }
          }
          if (checkedCount === 0) {
            $mtree.treeview("uncheckNode", [parentNode.nodeId, {
              silent: true
            }]);
            //setParentNodeUnCheck(parentNode);
          }
        }
      }
    });

    function SubmitMethod(jobj) {
      var formData = $('#EditForm').serializeArray();
      var ts = [];
      var nodes = $("#menuTree").treeview("getChecked");
      for (var x in nodes) {
        ts.push(nodes[x].id);
      }
      if (ts.length == 0) {
        return false;
      }
      formData.push({
        "name": "mtree",
        value: ts.join(',')
      });
      var eidtUrl = currentUrl + "Roles";
      $.ajax({
        url: eidtUrl,
        type: 'PUT',
        data: formData,
        dataType: 'json',
        success: function (result) { //边缘弹出
          top.layer.alert(result.message, function (index) {
            if (result.status) {              
             jobj.bootstrapTable('refresh');
              top.layer.closeAll();
            }else {
              top.layer.close(index);
            }
          });
        }
      });
    }
  </script>
</body>

</html>